package com.innovation.ic.cyz.base.service.pve_standard.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.base.Strings;
import com.innovation.ic.cyz.base.mapper.pve_standard.*;
import com.innovation.ic.cyz.base.model.pve_standard.Brands;
import com.innovation.ic.cyz.base.model.pve_standard.CategoriesProperty;
import com.innovation.ic.cyz.base.model.pve_standard.Category;
import com.innovation.ic.cyz.base.model.pve_standard.Products;
import com.innovation.ic.cyz.base.model.pve_standard.ProductsProperty;
import com.innovation.ic.cyz.base.model.pve_standard.ProductsUnique;
import com.innovation.ic.cyz.base.pojo.constant.ProductConstants;
import com.innovation.ic.cyz.base.pojo.global.ApiPageResult;
import com.innovation.ic.cyz.base.pojo.global.ServiceResult;
import com.innovation.ic.cyz.base.pojo.variable.cyz.device_selection_parameter.DeviceSelectionParamPojo;
import com.innovation.ic.cyz.base.pojo.variable.cyz.device_selection_parameter.DeviceSelectionParameterQueryListRespPojo;
import com.innovation.ic.cyz.base.pojo.variable.pve_standard.ps_category.PsCategoryItemPojo;
import com.innovation.ic.cyz.base.pojo.variable.pve_standard.ps_category.PsCategoryResultPojo;
import com.innovation.ic.cyz.base.pojo.variable.pve_standard.ps_productsunique.PsProdsUniqPojo;
import com.innovation.ic.cyz.base.pojo.variable.pve_standard.ps_productsunique.PsProductQueryByBrandPartRespPojo;
import com.innovation.ic.cyz.base.pojo.variable.pve_standard.ps_property.*;
import com.innovation.ic.cyz.base.service.pve_standard.ProductSearchService;
import com.innovation.ic.cyz.base.vo.cyz.deviceSelectionParameter.DeviceSelectionParameterFuzzyQueryVo;
import com.innovation.ic.cyz.base.vo.pve_standard.ps_productsunique.PsPartNumbersQueryByContextVo;
import com.innovation.ic.cyz.base.vo.pve_standard.ps_productsunique.PsProdsUniqVo;
import com.innovation.ic.cyz.base.vo.pve_standard.ps_productsunique.PsProductQueryByIdVo;
import com.innovation.ic.cyz.base.vo.pve_standard.ps_property.PsPropertyVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 器件选型具体实现类
 */
@Service
@Transactional
public class ProductSearchServiceImpl extends ServiceImpl<ProductsMapper, Products> implements ProductSearchService {
    @Resource
    private ProductsMapper productsMapper;

    @Resource
    private ProductsPropertyMapper productsPropertyMapper;

    @Resource
    private CategoriesPropertyMapper categoriesPropertyMapper;

    @Resource
    private ProductsUniqueMapper productsUniqueMapper;

    @Resource
    private BrandsMapper brandsMapper;

    @Resource
    private CategoryMapper categoryMapper;

    @Resource
    private PcFilesMapper pcFilesMapper;

//    @Resource
//    private CategoriesPropertyCyzMapper categoriesPropertyCyzMapper;
//
//    @Resource
//    private CategoriesCyzMapper categoriesCyzMapper;

    /**
     * test1
     */
    @Override
    public ServiceResult test1() {
        Products products = productsMapper.selectById("PD2022021959509437");

        QueryWrapper<ProductsProperty> qwProductsProperty = new QueryWrapper<>();
        qwProductsProperty.lambda().eq(ProductsProperty::getId, "PD220624000056");
        List<ProductsProperty> productsPropertyList = productsPropertyMapper.selectList(qwProductsProperty);

        Category category = categoryMapper.selectById("C4105499");

        CategoriesProperty categoriesProperty = categoriesPropertyMapper.selectById("D01505796");

        ProductsUnique productsUnique = productsUniqueMapper.selectById("#458PT-1720=P3-ND");

        Brands brand = brandsMapper.selectById("B1029370");

        return null;
    }

    /**
     * 查询器件选型分类
     */
    @Override
    public ServiceResult<PsCategoryResultPojo> getPsCategories() {
        List<PsCategoryItemPojo> categories = new ArrayList<>();

        PsCategoryItemPojo c1 = new PsCategoryItemPojo();
        c1.setCategoryId("C4509085");
        c1.setCategoryName("单片机(MCU/MPU/SOC)");
        categories.add(c1);

        PsCategoryItemPojo c2 = new PsCategoryItemPojo();
        c2.setCategoryId("C4507247");
        c2.setCategoryName("DC-DC电源芯片");
        categories.add(c2);

        PsCategoryItemPojo c3 = new PsCategoryItemPojo();
        c3.setCategoryId("C4105537");
        c3.setCategoryName("专用传感器");
        categories.add(c3);

        PsCategoryResultPojo result = new PsCategoryResultPojo();
        result.setTops(categories);

        ServiceResult<PsCategoryResultPojo> serviceResult = new ServiceResult<>();
        serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(result);

        return serviceResult;
    }

    /**
     * 查询筛选参数
     *
     * @param psPropertyVo           器件选型属性的vo类
     * @param externallyUniqueIdList 器件选型类型包含参数id集合
     * @return 返回查询结果
     */
    @Override
    public ServiceResult<DeviceSelectionParameterQueryListRespPojo> getSelectProperties(PsPropertyVo psPropertyVo, List<String> externallyUniqueIdList) {
        // 查询属性信息
        List<DeviceSelectionParamPojo> psProperties = new ArrayList<>();
        if (externallyUniqueIdList != null && !externallyUniqueIdList.isEmpty()) {
            // 根据器件选型类型包含参数id集合查询分类对应属性表数据集合
            psProperties = productsPropertyMapper.getPropertysByIdList(externallyUniqueIdList);
            if (psProperties != null && psProperties.size() > 0) {
                List<String> propertyIds = psProperties.stream().map(DeviceSelectionParamPojo::getPropertyId).collect(Collectors.toList());

                List<ProductsProperty> productsPropertyList = productsPropertyMapper.findPropertyValuesByPropertyIds(propertyIds);

                psProperties = psProperties.stream().map(item -> {
                    List<ProductsProperty> thePropertyValues = productsPropertyList.stream()
                            .filter(t -> t.getPropertyID().equals(item.getPropertyId()))
                            .collect(Collectors.toList());
                    if (thePropertyValues != null && !thePropertyValues.isEmpty()) {
                        List<String> valueText = thePropertyValues.stream().map(t -> t.getText()).collect(Collectors.toList());
                        item.setValueText(valueText);
                    }
                    return item;
                }).collect(Collectors.toList());
            }
        }

        DeviceSelectionParameterQueryListRespPojo result = new DeviceSelectionParameterQueryListRespPojo();
        result.setProperties(psProperties);

        ServiceResult<DeviceSelectionParameterQueryListRespPojo> serviceResult = new ServiceResult<>();
        serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(result);
        return serviceResult;
    }

    /**
     * 根据分类查询备选属性值
     */
    @Override
    public ServiceResult<PsPropertyResultPojo> getPsProperties(PsPropertyVo psPropertyVo) {
        // 查询属性信息
        List<PsPropertyPojo> psProperties = productsPropertyMapper.findProperties(psPropertyVo.getCategoryId());
        if (psProperties != null && !psProperties.isEmpty()) {
            List<String> propertyIds = psProperties.stream().map(t -> t.getPropertyId()).collect(Collectors.toList());
            List<ProductsProperty> productsPropertyList = productsPropertyMapper.findPropertyValuesByPropertyIds(propertyIds);

            psProperties = psProperties.stream().map(item -> {
                List<ProductsProperty> thePropertyValues = productsPropertyList.stream()
                        .filter(t -> t.getPropertyID().equals(item.getPropertyId()))
                        .collect(Collectors.toList());
                if (thePropertyValues != null && !thePropertyValues.isEmpty()) {
                    List<String> valueText = thePropertyValues.stream().map(t -> t.getText()).collect(Collectors.toList());
                    item.setValueText(valueText);
                }
                return item;
            }).collect(Collectors.toList());
        }

        // 查询品牌信息
        List<PsPropertyBrandPojo> brands = brandsMapper.findBrands(psPropertyVo.getCategoryId());

        // 查询封装信息
        List<PsPropertyPackagePojo> packages = productsUniqueMapper.findPackages(psPropertyVo.getCategoryId());

        // 查询包装信息
        List<PsPropertyPackingPojo> packings = productsUniqueMapper.findPackings(psPropertyVo.getCategoryId());

        PsPropertyResultPojo result = new PsPropertyResultPojo();
        result.setProperties(psProperties);
        result.setBrands(brands);
        result.setPackages(packages);
        result.setPackings(packings);

        ServiceResult<PsPropertyResultPojo> serviceResult = new ServiceResult<>();
        serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(result);

        return serviceResult;
    }

    @Override
    public ServiceResult<ApiPageResult<PsProdsUniqPojo>> getPsProducts(PsProdsUniqVo param) {
        Page<ProductsUnique> p = new Page<>(param.getPageIndex(), param.getPageSize());

        IPage<PsProdsUniqPojo> data = productsUniqueMapper.getList(p, param);

        List<PsProdsUniqPojo> list = data.getRecords().stream().collect(Collectors.toList());

        ApiPageResult<PsProdsUniqPojo> pageResult = new ApiPageResult<>();
        pageResult.setList(list);
        pageResult.setPageNum(param.getPageIndex());
        pageResult.setPageSize(param.getPageSize());
        pageResult.setTotal(data.getTotal());
        pageResult.setTotalPage(Integer.valueOf(String.valueOf(data.getPages())));
        ServiceResult<ApiPageResult<PsProdsUniqPojo>> serviceResult = new ServiceResult<>();
        serviceResult.setResult(pageResult);
        serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        return serviceResult;
    }

    @Override
    public ServiceResult<List<PsProdsUniqPojo>> getPsProductsByUids(String[] ids) {

        ServiceResult<List<PsProdsUniqPojo>> serviceResult = new ServiceResult<>();
        serviceResult.setResult(productsUniqueMapper.getListByUids(ids));
        serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        return serviceResult;
    }

    @Override
    public ServiceResult<List<PsCategoryPropertyPojo>> getPsCategoriesProperty(String categoryId) {
        ServiceResult<List<PsCategoryPropertyPojo>> serviceResult = new ServiceResult<>();
        serviceResult.setResult(categoriesPropertyMapper.getPsCategoriesProperty(categoryId));
        serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        return serviceResult;
    }

    /**
     * 参数筛选模糊查询
     *
     * @param deviceSelectionParameterFuzzyQueryVo 参数筛选模糊查询的vo类
     * @return 返回查询结果
     */
    @Override
    public ServiceResult<List<String>> queryFuzzyParamSelectProperties(DeviceSelectionParameterFuzzyQueryVo deviceSelectionParameterFuzzyQueryVo) {
        ServiceResult<List<String>> serviceResult = new ServiceResult<>();
        serviceResult.setResult(productsPropertyMapper.queryFuzzyParamSelectProperties(deviceSelectionParameterFuzzyQueryVo));
        serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        return serviceResult;
    }

    /**
     * 根据品牌、型号查询器件
     *
     * @param psProductQueryByIdVo 查询条件
     * @return 返回查询结果
     */
    @Override
    public ServiceResult<PsProductQueryByBrandPartRespPojo> queryProductsByBrandPartNumber(PsProductQueryByIdVo psProductQueryByIdVo) {
        Map<String, String> map = new HashMap<>();
        map.put(ProductConstants.ID_FIELD, psProductQueryByIdVo.getId());
        PsProductQueryByBrandPartRespPojo result = productsUniqueMapper.queryProductsByBrandPartNumber(map);
        if (result != null && !Strings.isNullOrEmpty(result.getProductID())) {
            // 根据品牌、型号查询属性信息
            result.setProperties(getProperties(result.getProductID()));

            // 查询附件信息
            result.setFiles(pcFilesMapper.selectFilesByProductId(result.getProductID()));
        }

        ServiceResult<PsProductQueryByBrandPartRespPojo> serviceResult = new ServiceResult<>();
        serviceResult.setResult(result);
        serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        return serviceResult;
    }

    /**
     * 型号模糊查询
     *
     * @param psPartNumbersQueryByContextVo 型号模糊查询的vo类
     * @return 返回查询结果
     */
    @Override
    public ServiceResult<List<String>> queryPartNumbersByContext(PsPartNumbersQueryByContextVo psPartNumbersQueryByContextVo) {
        List<String> result = productsUniqueMapper.queryPartNumbersByContext(psPartNumbersQueryByContextVo);

        ServiceResult<List<String>> serviceResult = new ServiceResult<>();
        serviceResult.setResult(result);
        serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        return serviceResult;
    }

    /**
     * 获取器件参数
     *
     * @param productId 产品id
     * @return 返回查询结果
     */
    private List<PsProductPropertyRespPojo> getProperties(String productId) {
        return productsPropertyMapper.selectPropertyByProductId(productId);
    }
}